package apis

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/config"
	"gorm.io/gorm"
	"strconv"
	"strings"
	"time"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/pkg/util"
	"tuowei.com/pkg/xlog"
)

type ApiLearningList struct {
	Base
	api.Api
}

func (e ApiLearningList) Get(c *gin.Context) {
	s := service.ApiCourse{}
	req := dto.SysCourseGetById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var data models.ApiCourse
	err = s.Get(&req, &data)
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var studyStatistics models.SysCourseChapterCompletedRecord
	err, studentId := e.GetUser(&e.Api)
	if err != nil {
		xlog.Error(err)
		e.Error(401, err, err.Error())
		return
	}
	err = e.Orm.Table(studyStatistics.TableName()).Where("student_id = ?", studentId).First(&studyStatistics).Error
	if err != nil {
		studyStatistics = models.SysCourseChapterCompletedRecord{}
	}
	data.Curriculum, err = s.CourseWareTreeCall(req.CourseId, "course", studentId)
	data.TaskList, err = s.CourseWareTreeCall(req.CourseId, "task")
	if err != nil {
		xlog.Error("===========", err.Error())
	}
	learningStatistics := new(models.LearningStatistics)
	h, m, second := resolveTime(studyStatistics.TotalStudyDuration)
	learningStatistics.CumulativeLearning.TimeConsumingLearning = strconv.Itoa(h) + "时" + strconv.Itoa(m) + "分" + strconv.Itoa(second) + "秒"
	learningStatistics.CumulativeLearning.CompletedStudy = strconv.Itoa(studyStatistics.TotalCompletedChapterCount) + "节"
	h, m, second = resolveTime(studyStatistics.TodayStudyDuration)
	learningStatistics.StudyToday.TimeConsumingLearning = strconv.Itoa(h) + "时" + strconv.Itoa(m) + "分" + strconv.Itoa(second) + "秒"
	learningStatistics.StudyToday.CompletedStudy = strconv.Itoa(studyStatistics.TodayCompletedChapterCount) + "节"

	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	data.LearningStatistics = learningStatistics
	e.OK(data, "成功")
	return
}

func (e ApiLearningList) GetPages(c *gin.Context) {
	s := service.ApiLearningList{}
	req := dto.GetLearningListReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Form, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	count := int64(0)
	err, req.BuyerId = e.GetUser(&e.Api)
	if err != nil {
		xlog.Error(err)
		e.Error(401, err, err.Error())
		return
	}
	list := make([]models.LearningList, 0)
	err = s.GetPages(&req, &list, &count)
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//获取学习记录
	//var practiceRecordModel models.SysPracticeRecord
	practiceRecordList := make([]*models.PracticeRecordList, 0)
	arr := make([]int, 0)
	for _, v := range list {
		arr = append(arr, v.CourseId)
	}

	err = e.Orm.Debug().Where("ex_type = ?", 1).Where("obj_id in ?", arr).Find(&practiceRecordList).Error
	if err != nil {
		if !strings.EqualFold(err.Error(), gorm.ErrRecordNotFound.Error()) {
			xlog.Error(err)
			e.Error(500, err, err.Error())
			return
		}
	}

	arrList := make(map[int]int, len(practiceRecordList))
	for _, vs := range practiceRecordList {
		arrList[vs.ObjId] = vs.Status
	}

	for ks, value := range list {
		value.Status = arrList[value.CourseId]
		list[ks].StatusText = status_text(value.Status)
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
	return
}

func (e ApiLearningList) Insert(c *gin.Context) {
	s := service.ApiLearningList{}
	req := dto.SysLearningListInsertReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Form, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	if req.BuyerId == 0 {
		err, req.BuyerId = e.GetUser(&e.Api)
		if err != nil {
			xlog.Error(err)
			e.Error(401, err, err.Error())
			return
		}
	}
	list := &models.SysLearningList{}
	err = s.Insert(&req, list)
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	e.OK(req.BuyerId, "添加成功")
	return
}

func status_text(int2 int) string {
	status_str := ""
	switch int2 {
	case -1:
		status_str = "未开始"
	case 1:
		status_str = "进行中"
	case 2:
		status_str = "已完成"
	default:
		status_str = "未开始"
	}
	return status_str
}

func (e ApiLearningList) CourseLearnStatistics(c *gin.Context) {
	err := e.MakeContext(c).
		MakeOrm().
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err, studentId := e.GetUser(&e.Api)
	if err != nil {
		xlog.Error(err)
		e.Error(401, err, err.Error())
		return
	}
	var model models.SysCourseChapterCompletedRecord
	var data models.SysCourseChapterCompletedRecord
	err = e.Orm.Debug().Model(model).Where("student_id = ?", studentId).First(&data).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		data.StudentId = studentId
		data.TodayCompletedChapterCount = 1
		data.TotalCompletedChapterCount = 1
		data.ModelTime.CreatedAt = time.Now()
		err = e.Orm.Create(&data).Error
		if err != nil {
			e.Error(500, err, err.Error())
			return
		}
		e.OK(nil, "Success")
		return
	}
	updates := map[string]interface{}{
		"today_completed_chapter_count": gorm.Expr("today_completed_chapter_count  + ?", 1),
		"total_completed_chapter_count": gorm.Expr("total_completed_chapter_count  + ?", 1),
	}
	if err = e.Orm.Debug().Model(model).Where("student_id = ?", studentId).Updates(updates).Error; err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(nil, "Success")
	return
}

func (e ApiLearningList) StudyDurationStatistics(c *gin.Context) {
	req := dto.ChronographyReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var data models.SysCourseChapterCompletedRecord
	var duration int64
	err, studentId := e.GetUser(&e.Api)
	if err != nil {
		xlog.Error(err)
		e.Error(401, err, err.Error())
		return
	}
	keys := util.MakeStoreValueKey("today_duration", strconv.Itoa(studentId))
	if req.TimeType == "start" {
		now := time.Now().Unix
		strconv.FormatInt(now(), 10)
		err = config.GetRedisClient().Set(keys, strconv.FormatInt(now(), 10), time.Second*86400).Err()
		if err != nil {
			e.Error(500, err, err.Error())
			return
		}
		e.OK(nil, "Success")
		return

	} else if req.TimeType == "stop" {
		res, errs := config.GetRedisClient().Get(keys).Result()
		if errs != nil {
			xlog.Error(errs)
			e.Error(500, errs, "请先开始计时")
			return
		}

		ints, _ := strconv.ParseInt(res, 10, 64)
		duration = time.Now().Unix() - ints
		update := map[string]interface{}{
			"today_study_duration": gorm.Expr("today_study_duration + ?", duration),
			"total_study_duration": gorm.Expr("total_study_duration + ?", duration),
		}
		err = e.Orm.Debug().Table(data.TableName()).
			Where("student_id = ?", studentId).
			Updates(update).Error
		if errs != nil {
			xlog.Error(errs)
			e.Error(500, errs, err.Error())
			return
		}
		config.GetRedisClient().Del(keys)
		e.OK(nil, "Success")
		return
	} else {
		e.Error(500, errors.New("param is not exits"), "param is not exits")
		return
	}
}

func (e ApiLearningList) CompletedVideoStudyTiming(c *gin.Context) {
	//req := dto.LearnListVideoStudyReq{}
	s := service.ApiLearningList{}
	err := e.MakeContext(c).MakeOrm().MakeService(&s.Service).Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//s.GetPages()
}
